import 'package:get/get.dart';
import '../const/const.dart';

class ApiService extends GetConnect {

  Future<dynamic> post0(String url, Map<String, dynamic> reqBody) async {
    try {
      Get.log("post url: ${url}, req: ${reqBody}");
      await Future.delayed(const Duration(seconds: 1));
      Response<dynamic> response = await post("$host$url", reqBody);
      return parseRespData(response);
    } catch (e) {
      Get.log("post0Error ${e}");
    }
    Get.snackbar("出错了", "网络错误");
    return null;
  }

  Future<dynamic> post1(
      String url, String token, Map<String, dynamic> reqBody) async {
    try {
      Get.log("post url: ${url}, req: ${reqBody}");
      await Future.delayed(const Duration(seconds: 1));
      Response<dynamic> response = await post("$host$url", reqBody,
          headers: {"Authorization": "Bearer ${token}"});
      return parseRespData(response);
    } catch (e) {
      Get.log("post0Error ${e}");
    }
    Get.snackbar("出错了", "网络错误");
    return null;
  }

  Future<dynamic> get0(String url, String token) async {
    try {
      Get.log("get url: ${url}");
      await Future.delayed(const Duration(seconds: 1));
      Response<dynamic> response =
          await get("$host$url", headers: {"Authorization": "Bearer ${token}"});
      return parseRespData(response);
    } catch (e) {
      Get.log("get0Error ${e}");
    }
    Get.snackbar("出错了", "网络错误");
    return null;
  }

  dynamic parseRespData(Response<dynamic> value) {
    Get.log("resp: ${value.bodyString}");
    if (value.status.isOk) {
      var body = value.body;
      if ("200" != body["code"]) {
        Get.log("error: ${body["msg"]}");
        Get.snackbar("出错了", body["msg"] ?? "请求错误");
        return null;
      }
      var data = body["data"];
      return data;
    }

    Get.log("errorCode: ${value.status.code}");
    Get.snackbar("出错了", "网络错误");
    return null;
  }
}
